package com.fantastic.aspect;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fantastic.anno.RedisDynamicLock;
import com.fantastic.anno.VerifyProperties;
import com.fantastic.util.SpelUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : fantastic
 * @date : 2024/5/11 17:59
 * @desc : this class for xxxxx
 **/
@Component
@Aspect
@Slf4j
public class DynamicLockAspect {

    @Autowired
    private RedissonClient redissonClient;

    private static final String REDISSON_LOCK_PREFIX = "redisson_lock:";

    @Pointcut("@annotation(com.fantastic.anno.RedisDynamicLock)")
    public void pointcut() throws Throwable {

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取传入目标方法的参数对象
        Object[] args = joinPoint.getArgs();
        //获取封装了部署信息的对象，在该对象中可以获取到目标方法名，所属类的Class等信息
        Class<?> clazz = joinPoint.getTarget().getClass();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = clazz.getMethod(signature.getName(), signature.getParameterTypes());
        RedisDynamicLock ann = method.getAnnotation(RedisDynamicLock.class);
        //如果有需要则执行校验逻辑
        VerifyProperties[] properties = ann.verifyProperties();
        verify(properties, joinPoint.getTarget(), method, args);
        String lockKey = REDISSON_LOCK_PREFIX + ann.lockName() + StrUtil.COLON + SpelUtils.parse(joinPoint.getTarget(), ann.key(), method, args);
        log.info("thread={},分布式锁：key={}", Thread.currentThread().getName(), lockKey);
        RLock lock = redissonClient.getLock(lockKey);
        Object result = null;
        try {
            //lock会一直等待，知道获取到锁
            //lock.lock(ann.expire(), ann.timeUnit());
            //tryLock等待一定时间后不再等待直接抛出异常
            boolean isLock = lock.tryLock(ann.waitTime(), ann.expire(), ann.timeUnit());
            if (isLock) {
                //执行业务逻辑
                result = joinPoint.proceed();
            } else {
                //提示操作繁忙
                throw new RuntimeException("操作频繁！");
            }
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                log.info("Lock Released");
            }

        }
        return result;
    }

    /**
     * 执行校验逻辑
     *
     * @param properties
     * @param target
     * @param targetMethod
     * @param args
     * @return
     */
    public boolean verify(VerifyProperties[] properties, Object target, Method targetMethod, Object[] args) {
        if (ArrayUtil.isNotEmpty(properties)) {
            Map<String, String> propertyMap = new HashMap<>(16);
            for (VerifyProperties property : properties) {
                String express = property.express();
                String name = property.name();
                String value = SpelUtils.parse(target, express, targetMethod, args);
                propertyMap.put(name, value);
            }
            log.info("获取到校验参数；{}", JSONUtil.toJsonStr(propertyMap));
        }
        return true;
    }
}
